package middlewares

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
)


func CookieMiddlerWare() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		cookie, err := ctx.Cookie("username")
		if err != nil {
			ctx.Redirect(http.StatusFound, "/ttsx/index")
			ctx.Abort()
			return
		}

		if cookie == "" {
			ctx.Redirect(http.StatusFound, "/ttsx/index")
			ctx.Abort()
			return
		}

		var NewCookieUser model.User
		if ret := global.App.DB.Where("name = ?", cookie).Find(&NewCookieUser); ret.RowsAffected == 0 {
			ctx.Redirect(http.StatusFound, "/ttsx/index")
			ctx.Abort()
			return
		}
		// 设置http请求头 和 获取http请求头
		// ctx.Request.Header.Set("token", cookie)
		// token := ctx.Request.Header.Get("token")

		ctx.Set("uid", NewCookieUser.ID)
		ctx.Set("username", NewCookieUser.Name)
		ctx.Set("IsActive", NewCookieUser.IsActive)
		ctx.Next()
	}
}
